package com.welab.pandahelper.utils;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class httpUtils {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client = new OkHttpClient();
    private static Gson gson = new Gson();

    public static Response get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

    public static Response get(String url,Map<String,String>headMap) throws IOException {
        Headers setHeaders = SetHeaders(headMap);
        Request request = new Request.Builder()
                .url(url)
                .headers(setHeaders)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }

    public static Response post(String url , String json, Map<String, String> headMap) throws IOException{

        RequestBody requestBody =  RequestBody.create(MediaType.parse("application/json"),json);
        Headers setHeaders = SetHeaders(headMap);
        Request.Builder builder = new Request.Builder();
        Request request = new Request.Builder()
                .url(url)
                .headers(setHeaders)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }


    public static Headers SetHeaders(Map<String, String> headersParams) {
        Headers headers = null;
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        if (headersParams != null) {
            Iterator<String> iterator = headersParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                headersbuilder.add(key, headersParams.get(key));
            }
        }
        headers = headersbuilder.build();
        return headers;
    }

}
